package com.competition.web.admin.service.impl;

import javax.annotation.Resource;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.admin.param.contract.IOrganizeRequestParam;
import com.competition.web.admin.service.IConditionService;
import com.competition.web.constant.RedisConstant;
import com.msg.ResponseCode;
import com.returns.value.CodeAndData;
import com.returns.value.ICodeAndData;
import com.unify.type.DepartmentFlatten;

/**
 * 实现条件服务
 */
@Service
public class ConditionServiceImpl implements IConditionService {

	private RedisTemplate<String, Object> redisTemplate;

	@Resource
	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	@Override
	public ICodeAndData<DepartmentFlatten[][]> getDesignatedNegotiatorAndInvitationDepartment(
			IOrganizeRequestParam organizeRequestParam, String token) {
		
		redisTemplate.delete(RedisConstant.getEligibleKey(token));
		ICodeAndData<DepartmentFlatten[][]> organize = this.getOrganize(organizeRequestParam);

		if (organize.getStatus() == ResponseCode.ERROR.getCode()) {
			return organize;
		}

		DepartmentFlatten[][] data = organize.getData();

		return new CodeAndData<>(data);
		
	}
	
	private ICodeAndData<DepartmentFlatten[][]> getOrganize(IOrganizeRequestParam organizeRequestParam) {

		String key = RedisConstant.getOrganizeKey();
//
		ListOperations<String, Object> listOperations = this.redisTemplate.opsForList();

		Long size = listOperations.size(key);

		if (null == size || 0 == size) {
			return new CodeAndData<>("失败，没有人员", ResponseCode.ERROR.getCode());
		}

		DepartmentFlatten[][] departmentFlattens = new DepartmentFlatten[2][];

		int len = size.intValue();
		
		DepartmentFlatten[] flattens = new DepartmentFlatten[len];
		
		for (int i = 0; i < size; i++) {

			flattens[i] = (DepartmentFlatten) listOperations.index(key, i);
		}
		departmentFlattens[0] = flattens;
		
		
		Long sizeErdao = listOperations.size(RedisConstant.DESIGNATED_NEGOTIATOR);
		
		DepartmentFlatten[] erdaoList = new DepartmentFlatten[sizeErdao.intValue()];
		
		for (int i = 0; i < sizeErdao; i++) {
			
			erdaoList[i] = (DepartmentFlatten) listOperations.index(RedisConstant.DESIGNATED_NEGOTIATOR, i);
		}
		
		departmentFlattens[1] = erdaoList;

		return new CodeAndData<>(departmentFlattens);
	}

}
